<template>
  <div class="container">
    <el-row :gutter="20">
      <!-- 左侧用户树 -->
      <el-col :span="8" :offset="0">
        <el-card shadow="always" :body-style="{ padding: '20px' ,'height':offsetHeight+'px','overflow-y': 'scroll' }">
          <el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
        </el-card>
      </el-col>
      <!-- 右侧用户详情 -->
      <el-col :span="16" :offset="0">
        <el-form :model="searchList" ref="searchList" size="normal">
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="">
                <el-input v-model="searchList.loginname" placeholder="登录名" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="">
                <el-input v-model="searchList.mobile" placeholder="手机号" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <div class="right">
                <el-button type="primary" size="default" @click="search">
                  查询
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>

        <!-- table表格 -->
        <el-table :data="tableData.results" border stripe :height="offsetHeight-80" v-loading="loading" ref="tableData">
          <!-- <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column> -->
          <el-table-column prop="company_name" label="归属公司" align="center">
          </el-table-column>
          <el-table-column prop="login_name" label="登录名" align="center">
          </el-table-column>
          <el-table-column prop="name" label="名称" align="center">
          </el-table-column>
          <el-table-column prop="mobile" label="手机" align="center">
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="{row}">
              <el-button type="primary" size="mini" @click="onEdit(row)">修改</el-button>
              <el-button type="danger" size="mini" @click="onRemove(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="page">
          <el-pagination @size-change="pageSizeChange" @current-change="pageNoChange" :page-sizes="[10, 50, 100, 200]"
            :page-size="10" background layout="total, sizes, prev, pager, next" :total="tableData.totalRecord">
          </el-pagination>
        </div>
      </el-col>
    </el-row>

    <el-drawer title="账号信息" :visible.sync="accountShow" size="70%" :before-close="cancel" center
      :destroy-on-close="true" :wrapperClosable="false">
      <div class="container">
        <el-alert title="密码组成位大小写字母加数组，最短为8位" type="error" effect="light" show-icon closable></el-alert>

        <el-form :model="accountList" ref="accountList" :rules="rules" label-width="120px" :inline="false"
          size="normal">
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="归属公司:">
                <el-input v-model="accountList.company_name" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="登录手机:" prop="mobile">
                <el-input v-model="accountList.mobile" placeholder="登录手机号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="登录名:">
                <el-input v-model="accountList.login_name" placeholder="登录名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="工号:">
                <el-input v-model="accountList.no" placeholder="工号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="姓名:" prop="name">
                <el-input v-model="accountList.name" placeholder="姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="邮箱:">
                <el-input v-model="accountList.email" placeholder="邮箱"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="密码:" prop="password">
                <el-input v-model="accountList.password" type="password" placeholder="密码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="确认密码:" prop="passwordc">
                <el-input v-model="accountList.passwordc" type="password" placeholder="密码"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="电话:">
                <el-input v-model="accountList.phone" placeholder="电话"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="允许登录:" prop="login_flag">
                <el-radio-group v-model="accountList.login_flag">
                  <el-radio-button label="1" border>是</el-radio-button>
                  <el-radio-button label="0" border>否</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item label="用户类型:">
                <el-select v-model="accountList.user_type" value-key="service_method_params" placeholder="用户类型"
                  class="wid">
                  <el-option value="1" label="系统管理"></el-option>
                  <el-option value="2" label="部门经理"></el-option>
                  <el-option value="3" label="普通用户"></el-option>
                  <el-option value="4" label="接口对接"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0"></el-col>
          </el-row>
          <el-form-item label="用户角色:">
            <el-checkbox-group v-model="accountList.rolelist">
              <el-checkbox v-for="item in userRole" :key="item.id" :label="item.id">
                {{item.name}}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="备注:">
            <el-input v-model="accountList.remarks" placeholder="电话" type="textarea" :rows="4"></el-input>
          </el-form-item>
          <el-form-item label="时间:">
            {{accountList.update_date}}
          </el-form-item>
        </el-form>
        <div class="center">
          <el-button type="danger" size="medium" @click="cancel">取消</el-button>
          <el-button type="primary" size="medium" @click="onUpdate">更新</el-button>
        </div>
      </div>

    </el-drawer>
  </div>
</template>

<script>
export default {
  name: '',
  components: {},
  props: {},
  data () {
    return {
      offsetHeight: document.documentElement.clientHeight - 150,
      loading: false,
      searchList: {},
      tableData: [],
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label',
        name: 'name',
      },
      companyId: '',
      pageNo: '1',
      pageSize: '10',
      accountShow: false,
      accountList: {},
      // 用户角色
      userRole: [],
      rules: {
        name: [
          { required: true, message: '请填写登录名', trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: this.$util.isPhone, trigger: 'blur' }
        ],
        login_flag: [
          { required: true, message: '请选择是否可以登录', trigger: 'change' }
        ],
        password: [
          { required: true, validator: this.$util.isPsd, trigger: 'blur' }
        ],
        passwordc: [
          { required: true, validator: this.$util.isPsd, trigger: 'blur' }
        ],
      },
    }
  },
  created () {
  },
  mounted () {
    this.init()
  },
  methods: {
    async init () {
      this.loading = true
      // 获取用户信息
      const res = await this.$http('sysUserList', {
      })

      let treelist = res
      for (let i = 0; i < treelist.length; i++) {
        treelist[i].label = treelist[i].name
      }
      this.treeData = this.toTree(treelist, 'children', 'id', 'parent_id')
      this.loading = false
    },
    // 获取用户权限
    async getRole () {
      const res = await this.$http('sysUserRole', {
        flag: '1',
        company_id: this.companyId
      })
      this.userRole = []
      res.forEach(item => {
        this.userRole.push({
          id: item.id,
          name: item.name
        })
      })
    },
    // 获取账号信息
    async getAccount () {
      const res = await this.$http('sysUserPage', {
        id: this.companyId,
        ...this.searchList,
        pageSize: this.pageSize,
        pageNo: this.pageNo,
        del_flag: 0
      })
      this.tableData = res
    },
    search () {
      this.getAccount()
    },
    async handleNodeClick (data) {
      this.companyId = data.id
      this.loading = true
      await this.getRole()
      await this.getAccount();
      this.loading = false
    },
    async onEdit (item) {
      await this.getRole()
      const res = await this.$http('sysUserObj', {
        contain_role: '1',
        ...item
      })

      if (res.rolelist) {
        // 多维度转换一维数组
        res.rolelist = this.$util.arrsToArr(res.rolelist, 'id')
      } else {

      }
      this.accountList = res
      this.accountShow = true
      // this.rolelist = []
      // 获取用户信息
      // this.getForUserList()
      // 绑定菜单
      // this.obj = ret.data.data
      // this.updaterow = ret.data.data
      // if (result.data.rolelist) {
      //   result.data.rolelist.forEach(item => {
      //     this.border.push(item.name)
      //   })
      // }

    },
    async onRemove (id) {
      this.loading = true
      this.$confirm('是否确认删除', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(async () => {
        const res = this.$http('sysUserEdit', {
          id: id, del: '1'
        })
        this.$tips.success(res.errmsg)
        this.getAccount()
        this.loading = false
      }).catch(() => {
        this.loading = false
      });
    },
    async onUpdate () {
      this.loading = true
      if (this.accountList.password !== this.accountList.passwordc) {
        this.$tips.error('密码两次输入不一致')
        this.loading = false
        return false
      }
      this.$refs['accountList'].validate(async (valid) => {
        if (valid) {
          let role = []
          let roleAll = this.$util.arrToStr(this.accountList.rolelist)
          this.userRole.forEach(item => {
            if (roleAll.indexOf(item.id) > -1) {
              role.push(item)
            }
          })
          const res = await this.$http('sysUserEdit', {
            ...this.accountList,
            rolelist: role,
          })
          this.$tips.success(res.errmsg)
          this.cancel()
          this.init()
        } else {
          this.$tips.error('请检查必填项')
          this.loading = false
          return false;
        }
      })
    },
    cancel () {
      this.accountShow = false
    },
    // table分页
    pageNoChange (pageNo) {
      this.pageNo = pageNo
      this.getAccount()
    },
    pageSizeChange (pageSize) {
      this.pageSize = pageSize
      this.getAccount()
    },
    // 菜单遍历重组结构
    toTree (data, children_key, id_key, pid_key) {
      let child_key = children_key || 'children'
      let id = id_key || 'id'
      let pid = pid_key || 'pid'
      // 删除无用子节点
      data.forEach(item => {
        delete item[child_key]
      })
      // 定义map,给map赋值
      let map = {}
      data.forEach(item => {
        map[item[id]] = item
      })
      // 遍历处理
      let arr = []
      data.forEach(item => {
        // 定义父节点
        let parent = map[item[pid]]
        if (parent) {
          (parent[child_key] || (parent[child_key] = [])).push(item)
        } else {
          arr.push(item)
        }
      })
      return arr
    },
  },
  computed: {
  }
}
</script>
<style lang='scss' scoped>
</style>